package com.hopes.bizz.risk.transfer.helper;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.hopes.bizz.common.core.util.StringUtils;
import com.hopes.bizz.risk.transfer.constant.RiskConstant;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.regex.Pattern;

/**
 * @author lyb
 * @version 1.0
 * @date 2024/1/31 17:16
 */
@Slf4j
public class RiskAuthorizationValidation {

    private final String authCode;

    public RiskAuthorizationValidation(String authCode) {
        this.authCode = authCode;
    }

    public Boolean checkFormat() {
        // 校验为空
        if (StringUtils.isBlank(authCode)) {
            log.info("认证token为空");
            return false;
        }
        // 校验长度
        int len = authCode.length();
        if (len != (RiskConstant.COMPANY_CODE_LEN + RiskConstant.TOKEN_DATE_LEN)) {
            log.info("认证token长度不正确");
            return false;
        }
        String dateStr = getRequestDateStr();
        Pattern pattern = Pattern.compile("[0-9]*");
        if (!pattern.matcher(dateStr).matches()) {
            log.info("认证token时间格式不正确");
            return false;
        }
        return true;
    }

    public Boolean checkExpired() {
        Date requestDate = getRequestDate();
        Date now = new Date();
        DateTime expiredDate = DateUtil.offsetHour(now, -RiskConstant.TOKEN_VALIDITY);
        if (DateUtil.compare(expiredDate, requestDate) > 0) {
            log.info("token已失效");
            return false;
        }
        if (DateUtil.compare(requestDate, now) > 0) {
            log.info("token请求时间大于当前系统时间");
            return false;
        }
        return true;
    }

    private String getRequestDateStr() {
        return authCode.substring(RiskConstant.COMPANY_CODE_LEN);
    }

    public Date getRequestDate() {
        return DateUtil.parse(getRequestDateStr(), RiskConstant.FORMAT_TOKEN_DATE);
    }

    public String getToken() {
        return authCode.substring(0, RiskConstant.COMPANY_CODE_LEN);
    }
}
